var trackerStore = null;
var  trackerHeader = "Please select a tracker";
var trackerGridPageBar = null;
var trackersGrid = null;
var previousSelections = null;
function reloadTrackerGrid(){
	g_seluin = null;
	//trackerGridPageBar.moveFirst();
	try{
		for(var p in gps_map){
			var gps = gps_map[p];
			if(gps.line != null){
				g_map.removePolyline(gps.line);
			}
			gps.line = null;
			if(gps.target_marker){
				if(gps.target_marker.popup){
	        		gps.target_marker.popup.destroy();
	        	}
				gps.target_marker.hide();
			}
			if(gps.lableText){
				gps.lableText.hideMe();
			}
        	
		}
	}catch(e){  }
	
	try{
		clearAlarmprompt();
		insertedAlarms = [];
	}catch(e){}
	
	var lastOptions = trackerStore.lastOptions;
	
	var userName = userAutocompleteCombo.getValue();
	var trackerName = trackersAutocompleteCombo.getValue();
	var trackerIME = trackersIMEAutocompleteCombo == null ? "":trackersIMEAutocompleteCombo.getValue();
	
	Ext.apply(lastOptions.params, {
		userid:(typeof trackerUserid == "undefined" ? "-1":trackerUserid),
		userName:encodeURI(userName),
		trackerName:encodeURI(trackerName), 
		trackerIME:trackerIME,
		action:'search'
	});
	//console.log(lastOptions);
	
	trackerStore.reload(lastOptions);
	Ext.apply(trackerStore.baseParams, lastOptions.params);
	//trackersGrid.getView().refresh();
	
	
	
}

//Ext.onReady(
		function createSearchGrid(){
	
	var trackerUrl = './childrenTrackers.jsp';
    
	// NOTE: This is an example showing simple state management. During development,
    // it is generally best to disable state management as dynamically-generated ids
    // can change across page loads, leading to unpredictable results.  The developer
    // should ensure that stable state ids are set for stateful components in real apps.    
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    /**
     * Custom function used for column renderer
     * @param {Object} val
     */
    function change(val){
        if(val > 0){
            return '<span style="color:green;">' + val + '</span>';
        }else if(val < 0){
            return '<span style="color:red;">' + val + '</span>';
        }
        return val;
    }

    /**
     * Custom function used for column renderer
     * @param {Object} val
     */
    function pctChange(val){
        if(val > 0){
            return '<span style="color:green;">' + val + '%</span>';
        }else if(val < 0){
            return '<span style="color:red;">' + val + '%</span>';
        }
        return val;
    }

//var url = './testdata.jsp';    
var proxy = new Ext.data.HttpProxy({
        method: 'GET',
        prettyUrls: false,
        url:trackerUrl , // see options parameter for Ext.Ajax.request
        api: {
            // all actions except the following will use above url
            create  : trackerUrl,
            update  : trackerUrl
        }
});


//    // create the data store


// create the Data Store
trackerStore = new Ext.data.JsonStore({
    root: 'models',
    totalProperty: 'totalCount',
    idProperty: 'modelId',
    remoteSort: true,
    autoLoad:false,
    baseParams:{userid:-1},
    fields: [
        'model', 'uin','name','plugin','trackerId','userName','trackerName','carModelId'
    ],

    // load using script tags for cross domain, if the data in on the same domain as
    // this page, an HttpProxy would be better
    proxy:proxy
});



trackerStore.addListener("create", function(){
	
	//grid.getSelectionModel().selectFirstRow();
});
    // manually load local data
var options = {params:{start:0, limit:(typeof gridPageSize == 'undefined' ? 10000:gridPageSize),userid:(typeof trackerUserid == "undefined" ? "-1":trackerUserid)}};
	
trackerStore.load(options);
Ext.apply(trackerStore.baseParams, options.params);

	var sm = new Ext.grid.CheckboxSelectionModel({
	    listeners: {
	    // On selection change, set enabled state of the removeButton
	    // which was placed into the GridPanel using the ref config
	    selectionchange: function(m) {
	        if (m.getCount()) {
	            //grid4.removeButton.enable();
	        } else {
	            //grid4.removeButton.disable();
	        }
	        var datas = m.getSelections();
	        //console.log(datas);
	        selectedTrackers = [];
	        for(var i = 0; i < datas.length; i++){
	        	selectedTrackers.push(datas[i].data.uin);
	        	if(previousSelections.containsKey(datas[i].data.uin)){
	        		previousSelections.removeKey(datas[i].data.uin);
	        	}
	        	//gpstracker_map[datas[i].data.uin] = datas[i].data;
	        }
	    },
	    checkOnly:true
	},
	singleSelect:false
	});

	var pagingBar = new Ext.PagingToolbar({
        pageSize: (typeof gridPageSize == 'undefined' ? 10:gridPageSize),
        store: trackerStore,
        displayInfo: true,
        displayMsg: '',
        emptyMsg: "",
        beforePageText:beforePageText,
        refreshText:refreshText,
        afterPageText:afterPageText,
        items:[
            '-', {
            pressed: true,
            enableToggle:true,
            text: '',
            cls: 'x-btn-text-icon details',
            toggleHandler: function(btn, pressed){
                var view = grid.getView();
                view.showPreview = pressed;
                
                view.refresh();
            }
        }]
    });
	
	pagingBar.addListener("beforechange", function(){
		//console.log(9999);
		if(previousSelections == null){
			previousSelections = new Ext.util.MixedCollection();
		}
		if(selectedTrackers != null){
			for(var i = 0; i < selectedTrackers.length; i++){
				if(!previousSelections.containsKey(selectedTrackers[i]))
					previousSelections.add(selectedTrackers[i], gpstracker_map[selectedTrackers[i]]);
				else{
					
				}
			}
		}
		//console.log('before change ppoo000',previousSelections);
	});
	
    // create the Grid
    var grid = new Ext.grid.GridPanel({
        store: trackerStore,
        columns: [
// <option value='<%=trackers.get(i).getUserTrackerId()%>' ><%=trackers.get(i).getTrackerName()%> - <%=trackers.get(i).getModelName()%> - <%=trackers.get(i).getUserTrackerId()%></option>		
            //{id:'uin',header: '&nbsp;',dataIndex:'',width:20,sortable: false, menuDisabled:true,resizable: false},
            sm,
			{id:'trackerId',header: trackerHeader,dataIndex:'name',sortable: false, menuDisabled:true,resizable: false}
        ],
        sm: sm,
        columnLines: true,
        stripeRows: false,
        height: (typeof gridHeight == 'undefined' ? '100%':gridHeight),
        width: 232,
        title: '',
        // config options for stateful behavior
        stateful: false,
        stateId: 'grid',
        enableDragDrop:false,
        cls:'grid-outline',
     // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:false,
            showPreview:false,
            autoScroll:false, 
            scrollOffset: 2,
            getRowClass : function(record, rowIndex, p, store){
                if(this.showPreview){
                    p.body = '<p>'+record.data.excerpt+'</p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
        },
        autoFitColumns: true
        // paging bar on the bottom
       // bbar: pagingBar

    });
//    grid.addListener("rowclick",function(g, rowIndex, e){
//    	console.log(arguments,g.store.getAt(rowIndex).data);
//    });
    
    trackerStore.addListener("load", function(records, dataArray, option){
    	//console.log(arguments," load");
    	var selModel = grid.getSelectionModel();//.selectFirstRow(); 
    	if(previousSelections == null){
			previousSelections = new Ext.util.MixedCollection();
		}
    	try{
    		for(var ii = 0 ; ii < dataArray.length; ii++){
    			var data = dataArray[ii].data;
    			//gpstracker_map[data.uin] = data;
    			if(previousSelections.containsKey(data.uin)){
    				selModel.selectRow(ii,true);
    				previousSelections.removeKey(data.uin);
    			}
    		}
    		//selModel.selectAll();
    		
    	}catch(e){}
    	try{
    		
    		gpstracker_map = new Array();
    		
    		var callFn = function(){
				try{
		    		if(dataArray[0]){
		    			if(typeof onSelTargetChange == 'function'){
		    				if(prevSelectedIMEI.length > 0){
		    	            	//
		    	            }else{
//		    	            	onSelTargetChange.call(top, dataArray[0].data.uin);
		    	            }
		    	    	}
		    			
		    	    	if(typeof onTrackerSelect == 'function'){ // For history page.
//		    	    		if(document.getElementById("uin").value == '')
//		    	    			onTrackerSelect.call(top, dataArray[0].data);
		    	    	}
		    		}
	    		}catch(e2){ window.setTimeout(callFn, 3000); }
    		};
    		
    			window.setTimeout(callFn, 3000);
    		for(var ii = 0 ; ii < dataArray.length; ii++){
    			var data = dataArray[ii].data;
    			data.rowIndex = ii;
    			gpstracker_map[data.uin] = data;
    		}
    	}catch(e){  }
    	if(previousSelections.length ==0 && (typeof selectedTrackers =='undefined' || selectedTrackers.length ==0)){
    		//selModel.selectFirstRow();
    	}
    	
    });    
    
    grid.getSelectionModel().addListener("rowselect",function(selModel, rowIndex, record){
    	//console.log(arguments, record);
    	if(typeof onSelTargetChange == 'function'){
			onSelTargetChange.call(top,record.data.uin);
    	}
    	if(typeof onTrackerSelect == 'function'){
    		onTrackerSelect.call(top,record.data);
    	}
    });
    
    grid.getSelectionModel().addListener("rowdeselect",function(selModel, rowIndex, record){
//    	console.log(arguments, record, " deselect");
    	if(typeof onDeSelTargetChange == 'function'){
    		onDeSelTargetChange.call(top,grid.store.data.items[rowIndex].data.uin);
    	}
    });
    
   /* grid.addListener("rowclick", function(grid, rowIndex, e){
    	//console.log(grid.store.data.items[rowIndex].data, rowIndex, e);
    	if(typeof onSelTargetChange == 'function'){
			onSelTargetChange.call(top,grid.store.data.items[rowIndex].data.uin);
    	}
    	if(typeof onTrackerSelect == 'function'){
    		onTrackerSelect.call(top,grid.store.data.items[rowIndex].data);
    	}
    });*/
    
    // render the grid to the specified div in the page
    grid.render('grid-trackers');
    
    var gconf = {};
    grid.cloneConfig(gconf);
    trackerGridPageBar = gconf.bbar; 
    
    trackersGrid = grid;
    
} //);
	
// 在左边突出在线车辆		
function setHighLightOnLeftGrid(uin/*the imei*/){
	var datas = trackersGrid.store.data.items;//[rowIndex].data
	for(var row = 0; row < datas.length; row++)
	{
		if(datas[row].data.uin == uin){
			var view = trackersGrid.getView();
			var rowHtml = view.getCell(row, 1);
			rowHtml.childNodes[0].style.color = 'green';
			break;
		}
	}
}
// 在左边不突出在线车辆
function setNormalOnLeftGrid(uin /*the imei*/){
	var datas = trackersGrid.store.data.items;//[rowIndex].data
	for(var row = 0; row < datas.length; row++)
	{
		if(datas[row].data.uin == uin){
			var view = trackersGrid.getView();
			var rowHtml = view.getCell(row, 1);
			rowHtml.childNodes[0].style.color = '';
			break;
		}
	}
}